package com.easybbs.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import com.easybbs.config.WebConfig;
import com.easybbs.constants.Constants;
import com.easybbs.controller.base.ABaseController;
import com.easybbs.entity.enums.OperRecordOpTypeEnum;
import com.easybbs.entity.enums.ResponseCodeEnum;
import com.easybbs.entity.enums.UserRoleEnum;
import com.easybbs.entity.po.ForumArticle;
import com.easybbs.entity.po.ForumArticleAttachment;
import com.easybbs.entity.po.ForumBoard;
import com.easybbs.entity.po.UserInfo;
import com.easybbs.entity.query.ForumArticleQuery;
import com.easybbs.entity.vo.PaginationResultVO;
import com.easybbs.entity.vo.ResponseVO;
import com.easybbs.entity.vo.request.*;
import com.easybbs.entity.vo.response.ForumArticleGetUserDownloadInfoRspVO;
import com.easybbs.entity.vo.web.ForumArticleDetailVO;
import com.easybbs.entity.vo.web.ForumArticleDoLikeReqVO;
import com.easybbs.exception.BusinessException;
import com.easybbs.service.AccountService;
import com.easybbs.service.ForumArticleAttachmentService;
import com.easybbs.service.ForumArticleService;
import com.easybbs.service.ForumBoardService;
import com.easybbs.utils.StringTools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author: yudaxian
 * @Description: TODO
 * @DateTime: 2024/10/21 23:26
 **/
@RestController
@Api(tags = "论坛文章相关接口")
@RequestMapping("/forum")
@Slf4j
public class ForumArticleController extends ABaseController {

    @Resource
    private ForumArticleService forumArticleService;

    @Resource
    private AccountService accountService;

    @Resource
    private ForumArticleAttachmentService articleAttachmentService;

    @Resource
    private WebConfig webConfig;

    @Resource
    private ForumBoardService forumBoardService;


    @ApiOperation(value = "加载文章列表")
    @PostMapping("/loadArticle")
    @SaIgnore
    public ResponseVO loadArticle(@RequestBody @Validated ForumArticleLoadArticleReqVO reqVO) {
        return getSuccessResponseVO(forumArticleService.loadArticle(reqVO));
    }

    @PostMapping("/getArticleDetail/{articleId}")
    @SaIgnore
    @ApiOperation(value = "获取文章详情")
    public ResponseVO getArticleDetail(@PathVariable("articleId")
                                       @Validated
                                       @NotBlank(message = "文章ID不能为空")
                                       String articleId) {

        ForumArticleDetailVO articleDetailVO = forumArticleService.getArticleDetail(articleId);

        return getSuccessResponseVO(articleDetailVO);
    }

    @PostMapping("/doLike")
    @SaCheckLogin
    @ApiOperation(value = "点赞")
    public ResponseVO doLike(@RequestBody @Validated ForumArticleDoLikeReqVO reqVO) {

        UserInfo userInfo = accountService.getOnlyLoginUserInfo();
        forumArticleService.doLike(reqVO.getObjectId(), userInfo, OperRecordOpTypeEnum.getType(reqVO.getType()));

        return getSuccessResponseVO(null);
    }

    @PostMapping
    @SaCheckLogin
    @ApiOperation(value = "获取用户下载信息")
    public ResponseVO getUserDownloadInfo(@RequestBody @Validated ForumArticleFileIdReqVO reqVO) {

        ForumArticleGetUserDownloadInfoRspVO rspVO = forumArticleService.getUserDownloadInfo(reqVO.getFileId());

        return getSuccessResponseVO(rspVO);
    }

    @PostMapping("/attachmentDownload")
    @SaCheckLogin
    @ApiOperation(value = "下载附件")
    public void attachmentDownload(HttpServletRequest request, HttpServletResponse response,
                                   @RequestBody @Validated ForumArticleFileIdReqVO reqVO) {

        ForumArticleAttachment articleAttachment = articleAttachmentService.getForumArticleAttachmentByFileId(reqVO.getFileId());
        if (ObjectUtils.isEmpty(articleAttachment)) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        String path = webConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_ATTACHMENT + articleAttachment.getFilePath();
        String downloadFileName = articleAttachment.getFileName();
        File file = new File(path);
        if (!file.exists()) {
            throw new BusinessException("文件不存在");
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            response.setContentType("application/x-msdownload; charset=UTF-8");
            // 兼容不同的浏览器
            if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {
                // IE浏览器
                downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
            } else {
                // 其他浏览器
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            // 设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
            // 创建管道
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            log.error("下载附件失败", e);
            throw new BusinessException("下载附件失败");
        } finally {
            // 关闭流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("关闭输入流失败");
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("关闭输出流失败");
                }
            }
        }
    }

    @PostMapping("/loadBoard4Post")
    @SaCheckLogin
    @ApiOperation(value = "发布文章获取板块")
    public ResponseVO loadBoard4Post() {

        UserInfo loginUserInfo = accountService.getOnlyLoginUserInfo();

        Integer postType = null;

        if (!loginUserInfo.getRole().equals(UserRoleEnum.ADMIN.getRoleName())) {
            postType = 1;
        }

        List<ForumBoard> boardTree = forumBoardService.getBoardTree(postType);

        return getSuccessResponseVO(boardTree);
    }

    @PostMapping("/postArticle")
    @SaCheckLogin
    @ApiOperation(value = "发布文章")
    private ResponseVO postArticle(@RequestBody @Validated ForumArticlePostArticleReqVO reqVO) {

        String articleId = forumArticleService.postArticle(reqVO);

        return getSuccessResponseVO(articleId);
    }

    @SaCheckLogin
    @ApiOperation(value = "获取修改的文章详情")
    @PostMapping("/articleDetail4Update/{articleId}")
    public ResponseVO articleDetail4Update(
            @PathVariable("articleId") @Validated @NotBlank(message = "文章ID不能为空") String articleId
    ) throws BusinessException {

        ForumArticleDetailVO detailVO = forumArticleService.getArticleDetail4Update(articleId);

        return getSuccessResponseVO(detailVO);
    }

    @PostMapping("/updateArticle")
    @SaCheckLogin
    @ApiOperation(value = "修改文章")
    public ResponseVO updateArticle(
            @RequestBody @Validated ForumArticleUpdateArticleReqVO reqVO
    ) {
        String title = StringTools.eecpapeHtml(reqVO.getTitle());
        UserInfo loginUserInfo = accountService.getOnlyLoginUserInfo();
        ForumArticle forumArticle = new ForumArticle();

        forumArticle.setArticleId(reqVO.getArticleId());
        forumArticle.setpBoardId(reqVO.getPBoardId());
        forumArticle.setBoardId(reqVO.getBoardId());
        forumArticle.setTitle(title);
        forumArticle.setContent(reqVO.getContent());
        forumArticle.setMarkdownContent(reqVO.getMarkdownContent());
        forumArticle.setEditorType(reqVO.getEditorType());
        forumArticle.setSummary(reqVO.getSummary());
        forumArticle.setUserIpAddress(loginUserInfo.getLastLoginIpAddress());
        forumArticle.setAttachmentType(reqVO.getAttachmentType());
        forumArticle.setUserId(loginUserInfo.getUserId());
        // 附件信息
        ForumArticleAttachment forumArticleAttachment = new ForumArticleAttachment();
        forumArticleAttachment.setIntegral(reqVO.getIntegral() == null ? 0 : reqVO.getIntegral());
        articleAttachmentService.updateArticle(loginUserInfo.getRole().equals(UserRoleEnum.ADMIN.getRoleName()), forumArticle, forumArticleAttachment, reqVO.getCover(), reqVO.getAttachment());

        return getSuccessResponseVO(forumArticle.getArticleId());
    }

    @PostMapping("/search")
    @ApiOperation(value = "搜索文章")
    public ResponseVO search(@RequestBody @Validated ForumArticleSearchReqVO reqVO) {

        PaginationResultVO<ForumArticle> result = forumArticleService.search(reqVO.getKeyword());

        return getSuccessResponseVO(result);

    }

}
